<!--
 * @Author: weikang
 * @Description:
 * @Date: 2024-01-11 20:59:01
 * @LastEditTime: 2025-04-07 21:16:51
 * @FilePath: \env-manager-pc\src\views\electricity_statistics\EntDeviceTreeCheck\index.vue
-->

<script setup lang="ts">
import { debounce } from 'lodash-es'
import useEntStore from '@/store/modules/ent'
import { DeviceType } from '@/utils/dataHook/devices'
import { reverseData } from '@/utils/index'

const { entId, deviceId } = defineProps({
  entId: {
    type: String,
    default: '',
  },
  deviceId: {
    type: String,
    default: '',
  },
})

const emits = defineEmits(['currentChange'])
const entStore = useEntStore()

interface Tree {
  Name: string
  Children?: Tree[]
}

const propOptions = {
  children: 'Children',
  label: 'Name',
}

const currentEnt = ref(null)
const data = ref<Tree[]>([])
const treeRef = ref()

const idMap = ref<any>([])
watchEffect(() => {
  if (!entStore.currentEntData.baseInfo || !currentEnt.value) {
    return []
  }
  const child = [
    {
      Name: currentEnt.value.Name,
      Children: [
        {
          Name: '总表',
          Children: entStore.currentEntData.ElectricDevices || [],
        },
        {
          Name: '产污设施',
          Children: entStore.Produces || [],
        },
        {
          Name: '治理设施',
          Children: entStore.Reuses || [],
        },
      ],
    },
  ]
  if (!Array.isArray(currentEnt.value)) {
    data.value = child
    return
  }
  let tempData: any = []
  const findEndData = (data: any) => {
    data.forEach((item: any) => {
      if (item && item.Children) {
        findEndData(item.Children)
      }
      else {
        tempData = item
      }
    })
  }
  findEndData(currentEnt.value)
  tempData.Children = child

  nextTick(() => {
    treeRef.value?.filter()
  })
})

onMounted(async () => {
  const data = await entStore.getEntBaseInfo(entId)
  await entStore.refreshDevices(entId)
  const tempData = data.EnvOrg ? reverseData(data.EnvOrg) : data
  currentEnt.value = tempData
})

const checkChange = debounce(() => {
  const nodes = treeRef.value.getCheckedNodes()
  const deviceNodes = nodes.filter((item: any) => item.type === DeviceType.Electric)
  emits('currentChange', deviceNodes)
}, 1000)

function filterTree(value: any, data: any) {
  if (idMap.value.includes(data.ObjID)) {
    return false
  }
  else {
    idMap.value.push(data.ObjID)
    return true
  }
}
</script>

<template>
  <div class="h-[calc(100vh-125px)] overflow-y-auto">
    <el-tree ref="treeRef" v-loading="entStore.currentEntLoading" :filter-node-method="filterTree" :data="data" node-key="ObjID" show-checkbox highlight-current default-expand-all :current-node-key="deviceId" :props="propOptions" @check-change="checkChange" />
  </div>
</template>
